<template>
  <div class="edit-order">
    <h2>编辑订单</h2>
    <el-form :model="order" label-width="120px">
      <el-form-item label="订单管理员">
        <el-input v-model="order.order_admin" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="订单名称">
        <el-input v-model="order.order_name"></el-input>
      </el-form-item>
      <el-form-item label="订单价格">
        <el-input v-model="order.order_price" type="number" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="订单状态">
        <el-select v-model="order.order_status">
          <el-option label="未付款" :value="7"></el-option>
          <el-option label="支付待审核" :value="1"></el-option>
          <el-option label="待发货" :value="2"></el-option>
          <el-option label="已发货" :value="3"></el-option>
          <el-option label="已签收" :value="4"></el-option>
          <el-option label="审核未通过" :value="5"></el-option>
          <el-option label="已退货" :value="6"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="联系电话">
        <el-input v-model="order.order_phone"></el-input>
      </el-form-item>
      <el-form-item label="收货地址">
        <el-input v-model="order.order_address"></el-input>
      </el-form-item>
      <el-form-item label="省份">
        <el-select v-model="order.order_province" placeholder="请选择省份">
          <el-option v-for="province in provinces" :key="province" :label="province" :value="province"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="order.order_remark" type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="商品列表">
        <table class="goods-table">
          <thead>
            <tr>
              <th>商品ID</th>
              <th>商品名称</th>
              <th>商品数量</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(goods, index) in order.bs_order_goods" :key="index">
              <td>{{goods.goods_id}}</td>
              <td>{{goods.goods_name}}</td>
              <td>{{goods.goods_num}}</td>
            </tr>
          </tbody>
        </table>
      </el-form-item>
      
      <!-- 支付凭证操作区域 -->
      <el-form-item label="支付凭证">
        <div v-if="order.order_status === 7">
          <div>
            <input type="file" @change="handleFileChange" />
            <el-button v-if="selectedFile" type="danger" @click="clearSelectedFile">删除选择的图片</el-button>
          </div>
          <el-form-item label="支付ID">
            <el-input v-model="payId"></el-input>
          </el-form-item>
          <el-form-item label="支付编号">
            <el-input v-model="payNumber"></el-input>
          </el-form-item>
          <el-button type="primary" @click="uploadImage" :disabled="!selectedFile">上传支付凭证</el-button>
        </div>
        <div v-else>
          <p>支付成功</p>
          <el-form-item label="支付ID">
            <el-input v-model="order.pay_id" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="支付编号">
            <el-input v-model="order.pay_number" :disabled="true"></el-input>
          </el-form-item>
          <img v-if="imageData" :src="`data:image/jpeg;base64,${imageData}`" alt="支付凭证" style="max-width: 100%;">
        </div>
      </el-form-item>

      <!-- 录入物流信息区域 -->
      <div v-if="order.order_status === 2">
        <el-form-item label="物流名称">
          <el-input v-model="logisticsName"></el-input>
        </el-form-item>
        <el-form-item label="物流单号">
          <el-input v-model="logisticsNumber"></el-input>
        </el-form-item>
        <el-form-item label="物流发货时间">
          <el-date-picker
            v-model="logisticsTime"
            type="datetime"
            placeholder="选择物流发货时间"
          ></el-date-picker>
        </el-form-item>
        <el-button type="primary" @click="submitLogistics">提交物流信息</el-button>
      </div>

      <!-- 审核相关按钮 -->
      <el-form-item v-if="order.order_status === 1">
        <el-button type="primary" @click="approveOrder">审核通过</el-button>
        <el-button type="danger" @click="rejectOrder">审核不通过</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      order: {
        order_admin: '',
        order_name: '',
        order_price: 0,
        order_status: 1,
        order_phone: '',
        order_address: '',
        order_province: '',
        order_remark: '',
        bs_order_goods: [] ,
        pay_id: '', // 支付ID
        pay_number: '' // 支付编号// 商品列表
      },
      provinces: ['北京', '上海', '广东', '广西', '江苏', '浙江', '四川', '湖北', '河北', '河南', '云南', '辽宁', '黑龙江', '湖南', '安徽', '山东', '新疆', '甘肃', '山西', '内蒙古', '陕西', '吉林', '江西', '贵州', '海南', '宁夏', '青海', '西藏', '重庆', '天津'],
      selectedFile: null,
      imageData: '',
      payId: '',
      payNumber: '',
      logisticsName: '',
      logisticsNumber: '',
      logisticsTime: null
    };
  },
  created() {
    this.fetchOrder();
  },
  methods: {
    // 获取订单数据
    fetchOrder() {
      const orderId = this.$route.params.id; // 从路由参数中获取订单ID
      axios.get(`http://127.0.0.1:3005/order/getOrders`)
        .then(response => {
          if (response.data && response.data.res && response.data.res.result) {
            const orders = response.data.res.result;
            const targetOrder = orders.find(order => order.order_id === orderId);
            if (targetOrder) {
              this.order = targetOrder; // 填充表单数据
              if (targetOrder.order_status !== 7) {
                this.showImage(); // 如果订单已支付，显示支付凭证
              }
            } else {
              this.$message.error('未找到该订单');
            }
          } else {
            this.$message.error('订单数据格式错误');
          }
        })
        .catch(error => {
          console.error(error);
          this.$message.error('订单查询失败');
        });
    },
    // 审核通过，将状态更新为待发货
    approveOrder() {
      this.order.order_status = 2; // 待发货
      this.updateOrderStatus();
    },
    // 审核不通过，将状态更新为未支付，并删除支付数据
    rejectOrder() {
      const orderId = this.$route.params.id;

      // 调用接口删除支付数据
      axios.delete(`http://127.0.0.1:3005/order/deletepay/${orderId}`)
        .then(() => {
          this.$message.success('支付数据删除成功');
          // 更新订单状态为审核未通过
          this.order.order_status = 5; // 审核未通过
          this.updateOrderStatus();
        })
        .catch(error => {
          console.error(error);
          this.$message.error('支付数据删除失败');
        });
    },
    // 更新订单状态
    updateOrderStatus() {
      const orderId = this.$route.params.id;
      axios.post(`http://127.0.0.1:3005/order/updateOrder/${orderId}`, this.order)
        .then(() => {
          this.$message.success('订单状态更新成功');
          // 跳转到指定地址
          window.location.href = 'http://localhost:3000/ReviewOrderList';
        })
        .catch(error => {
          console.error(error);
          this.$message.error('订单状态更新失败');
        });
    },
    handleFileChange(e) {
      const file = e.target.files[0];
      if (file) {
        const fileSize = file.size / 1024; // 将文件大小转换为 KB
        if (fileSize > 40) {
          this.$message.error('图片大小不能超过40KB，请重新选择');
          this.clearSelectedFile();
          return;
        }
        this.selectedFile = file;
      }
    },
    clearSelectedFile() {
      this.selectedFile = null;
      const input = document.querySelector('input[type="file"]');
      if (input) {
        input.value = ''; // 清空 input 的值
      }
    },
    async uploadImage() {
      if (!this.selectedFile) {
        alert('请选择一张图片');
        return;
      }
      if (!this.payId || !this.payNumber) {
        alert('请输入支付ID和支付编号');
        return;
      }

      try {
        const compressedBlob = await this.compressImage(this.selectedFile);

        const reader = new FileReader();
        reader.readAsDataURL(compressedBlob);

        reader.onload = async () => {
          const base64Data = reader.result.split(',')[1];

          const data = {
            order_id: this.order.order_id,
            pay_id: this.payId,
            pay_url: base64Data,
            pay_number: this.payNumber
          };

          const response = await axios.post('http://127.0.0.1:3005/order/createpay', data);
          console.log('图片上传成功:', response.data);
          alert('图片上传成功');
          this.order.order_status = 1; // 更新订单状态为已完成
          this.updateOrder(); // 更新订单
        };

        reader.onerror = () => {
          console.error('图片读取失败');
          alert('图片读取失败');
        };
      } catch (error) {
        console.error('图片上传失败:', error);
        alert('图片上传失败');
      }
    },
    async showImage() {
      try {
        const response = await axios.get(`http://127.0.0.1:3005/order/getpay/${this.order.order_id}`);
        this.imageData = response.data.res.result.pay_url;
        this.order.pay_id = response.data.res.result.pay_id; // 获取支付ID
        this.order.pay_number = response.data.res.result.pay_number; // 获取支付编号
      } catch (error) {
        console.error('获取图片失败:', error);
        alert('获取图片失败');
      }
    },
    // 提交物流信息
    submitLogistics() {
      if (!this.logisticsName || !this.logisticsNumber || !this.logisticsTime) {
        this.$message.error('请填写完整的物流信息');
        return;
      }
      const data = {
        order_id: this.order.order_id,
        logistics_name: this.logisticsName,
        logistics_number: this.logisticsNumber,
        logistics_time: this.logisticsTime
      };
      axios.post('http://127.0.0.1:3005/order/logistics', data)
        .then(() => {
          this.$message.success('物流信息提交成功');
          this.order.order_status = 3; // 更新订单状态为已发货
          this.updateOrderStatus();
        })
        .catch(error => {
          console.error(error);
          this.$message.error('物流信息提交失败');
        });
    }
  }
};
</script>

<style scoped>
.edit-order {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-button {
  margin-top: 10px;
}

.goods-table {
  width: 100%;
  margin-bottom: 20px;
  border-collapse: collapse;
}

.goods-table th,
.goods-table td {
  border: 1px solid #ebeef5;
  padding: 8px;
  text-align: left;
}

.goods-table th {
  background-color: #f5f7fa;
}
</style>